package rpt

import (
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/process/common"
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/tpl"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/rpt"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/app-starter/server"
	"github.com/lishimeng/go-log"
	"net/http"
)

type AddReq struct {
	Description string `json:"description"`
	Template    string `json:"template,omitempty"`
	StartDate   string `json:"startDate,omitempty"`
	EndDate     string `json:"endDate,omitempty"`
}

func createRpt(ctx server.Context) {
	var err error
	var clients []db.AmazonLwa
	var resp app.Response
	var req AddReq

	err = ctx.C.ReadJSON(&req)
	if err != nil {
		log.Info(err)
		resp.Code = http.StatusInternalServerError
		ctx.Json(resp)
		return
	}

	rptTpl, err := tpl.GetTpl(req.Template)
	if err != nil {
		log.Info(err)
		resp.Code = http.StatusNotFound
		resp.Message = "no template:" + req.Template
		ctx.Json(resp)
		return
	}

	_, err = app.GetOrm().Context.QueryTable(new(db.AmazonLwa)).Limit(1).All(&clients)
	if err != nil {
		log.Info(err)
		resp.Code = http.StatusInternalServerError
		ctx.Json(resp)
		return
	}
	if len(clients) == 0 {
		resp.Code = http.StatusNotFound
		ctx.Json(resp)
		return
	}
	var client = clients[0]
	sdk, err := common.CreateSdk(client)
	if err != nil {
		log.Info(err)
		resp.Code = http.StatusInternalServerError
		ctx.Json(resp)
		return
	}
	rptConfig := rpt.GenReq(req.StartDate, req.EndDate, rptTpl)
	result, err := sdk.CreateReport(rptConfig)
	if err != nil {
		log.Info("create rpt failed")
		log.Info(err)
		resp.Code = http.StatusInternalServerError
		ctx.Json(resp)
		return
	}
	saveRpt(client.ClientId, result, rptTpl)
	resp.Code = http.StatusOK
	resp.Message = result.ReportId
	ctx.Json(resp)
}

func saveRpt(clientId string, rpt advertising.RptStatus, template rpt.Template) {

	var err error
	err = app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		var tmp db.AmazonRpt
		tmp.ClientId = clientId
		tmp.Name = rpt.Name
		tmp.RptId = rpt.ReportId
		tmp.RptState = rpt.Status
		tmp.RptCreateAt = rpt.CreatedAt
		tmp.RptUpdateAt = rpt.UpdatedAt
		tmp.AmazonRptDuration.StartDate = rpt.StartDate
		tmp.AmazonRptDuration.EndDate = rpt.EndDate

		tmp.AmazonRptFile.RptFileUrl = rpt.Url
		tmp.AmazonRptFile.RptFileSize = rpt.FileSize
		tmp.AmazonRptFile.RptFileExpireAt = rpt.UrlExpiresAt

		tmp.RptFailureReason = rpt.FailureReason
		tmp.TableChangeInfo.Status = db.RptStatusInit
		tmp.RptTemplateId = template.GetTplName()
		_, e = tx.Context.Insert(&tmp)
		return
	})
	if err != nil {
		log.Info("save rpt fail")
		log.Info(err)
		return
	}
	log.Info("save rpt success")
}
